package FenxiaoService

import (
	"context"
	"gdshop-back-end-go/client-api/app/request/FenxiaoReq"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/common/tools"
	"github.com/gogf/gf/frame/g"
)

func TeamList(ctx context.Context, parames *FenxiaoReq.TeamList) *response.JsonResponse {
	fuModel, err := GetFenxiaoUserModelByMemberId(ctx, int(parames.MemberId))
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	objDb := g.DB().Ctx(ctx).Model("member").Unscoped().As("m").Where("m.delete_at < 1")
	dbPrefix := g.Cfg().GetString("database.prefix")
	switch parames.Type {
	case 3: // 下下级分销商
		objDb.Where(g.Map{
			"m.id IN (SELECT member_id FROM " + dbPrefix + "fenxiao_user WHERE delete_at<1 AND status=1 AND parent_parent_id = ?)": fuModel.Id,
		})
		break
	case 2: // 下级分销商
		objDb.Where(g.Map{
			"m.id IN (SELECT member_id FROM " + dbPrefix + "fenxiao_user WHERE delete_at<1 AND status=1 AND parent_id = ?)": fuModel.Id,
		})
		break
	case 1: // 推荐会员
		objDb.Where(g.Map{
			"m.id IN (SELECT member_id FROM " + dbPrefix + "fenxiao_member_user_map WHERE fenxiao_user_id = ?)": fuModel.Id,
		})
	default:
		objDb.Where(g.Map{
			"m.id IN (SELECT member_id FROM " + dbPrefix + "fenxiao_member_user_map WHERE fenxiao_user_id = ?)": fuModel.Id,
		})
		break
	}
	count, err := objDb.Fields("1").Count()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	all, err := objDb.Fields("m.nickname,m.avatar").Page(parames.Page, parames.PageSize).All()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	return response.SuccessByRequestMessageData(nil, "成功", g.Map{
		"list":      all.List(),
		"page_info": tools.GetPageInfo(count, parames.Page, parames.PageSize),
	})
}
